<template>
  <div class="wrap">
    <div class="login">
      <p class="title">商城后台管理系统 — {{isShow?'注册':'登录'}}</p>
      <el-form :model="loginForm" :rules="rules" ref="ruleForm" style="margin-top: 30px;">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="用户名" clearable prefix-icon="el-icon-user-solid" @keyup.enter.native="enter"> </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <div></div>
          <el-input v-model="loginForm.password" placeholder="密码" show-password prefix-icon="el-icon-lock" @keyup.enter.native="enter"> </el-input>
        </el-form-item>
        <el-form-item v-if="isShow" prop="checkPass">
          <el-input v-model="loginForm.checkPass" placeholder="确认密码" show-password prefix-icon="el-icon-lock" @keyup.enter.native="enter"> </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <div class="flex">
            <el-input v-model="loginForm.code" placeholder="请输入验证码" prefix-icon="el-icon-check" @keyup.enter.native="enter"> </el-input>
            <img :src="codeImg" @click="getCode" class="code" />
          </div>
        </el-form-item>
        <el-button @click="loginBtn" :loading="loading" style="width: 100%;margin-top: 10px;" type="primary">{{isShow?'注册':'登录'}}</el-button>
      </el-form>
      <el-button @click="goTo(false)" type="text" style="float: right;" v-show="isShow">使用已有账户登录</el-button>
      <el-button @click="goTo(true)" type="text" style="float: right;" v-show="!isShow">立即注册</el-button>
    </div>
    <span class="floor">Copyright © 2018-2023 192.168.1.106 All Rights Reserved.</span>
  </div>
</template>

<script>

import { register, login, code, roleMenu } from '@/api/login';
import { setToken } from '@/utils/auth';
import router, { addDynamicRoutes } from '@/router'; // 引入路由和动态添加路由函数

export default {
  name: 'Login',
  data() {
    var validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'));
      } else {
        if (this.isShow) {
          if (value.length < 3) {
            callback(new Error('密码需大于3位'));
          } else {
            this.$refs.ruleForm.validateField('checkPass');
          }
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.loginForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      codeImg: '',//验证码
      isShow: false,//登录或注册
      loginForm: {
        username: 'admin',
        password: '123',
        code: undefined,
        checkPass: undefined
      },
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ validator: validatePass, trigger: 'blur' }],
        checkPass: [{ validator: validatePass2, trigger: 'blur' }],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      }
    };
  },
  created() {
    this.getCode();
  },
  methods: {
    // 去注册或去登录
    goTo(is) {
      this.reset();
      this.$refs.ruleForm.resetFields();
      this.isShow = is;
    },
    // 获取验证码
    getCode() {
      code().then(res => {
        this.codeImg = window.URL.createObjectURL(res);
      });
    },
    enter() {
      this.loginBtn();
    },

    //登录或注册
    loginBtn() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const request = this.isShow ? register(this.loginForm) : login(this.loginForm);
          this.loading = true;
          request.then(res => {
            if (res.code == 200) {
              this.loading = false;
              if (this.isShow) {
                this.$confirm(`恭喜你，您的账号${this.loginForm.username}注册成功！是否继续登录`, '系统提示', { type: 'success' }).then(() => {
                  this.getCode();
                  this.loginForm.code = undefined;
                  this.isShow = false;
                }).catch(err => { });
              } else {
                setToken(res.token);
                this.$store.dispatch('user/login', res.data);
                this.$success(res.msg);
                roleMenu({ userid: res.data.userid }).then(res => {
                  if (res.code == 200) {
                    const sortRoutes = (routes) => {
                      if (Array.isArray(routes)) {
                        routes.sort((a, b) => a.sort - b.sort);
                        routes.forEach(route => {
                          if (route.children && route.children.length > 0) {
                            sortRoutes(route.children);
                          }
                        });
                      }
                      return routes;
                    };
                    const sortedData = sortRoutes(res.data);
                    localStorage.setItem('router', JSON.stringify(sortedData));
                    this.$store.dispatch('user/router', sortedData);
                    // addDynamicRoutes(sortedData); // 调用动态添加路由函数
                    // this.$router.push("/index");
                    window.location.replace('/index');

                  }
                });
              }
            } else {
              // 登录失败
              this.loading = false;
              this.$error(res.msg);
              if (res.code == 0) {
                this.getCode();
              }
            }
          }).catch(err => {
            this.loading = false;
          });
        }
      });
    },

    reset() {
      this.loginForm.username = undefined;
      this.loginForm.password = undefined;
      this.loginForm.code = undefined;
      this.loginForm.checkPass = undefined;
    }
  },
}
</script>

<style lang="scss" scoped>
.code {
  width: 200px;
  margin-left: 10px;
  background: #eee;
  border: 1px solid #ddd;
  height: 40px;
  cursor: pointer;
}
.login {
  width: 350px;
  border-radius: 10px;
  background: #fff;
  padding: 30px 30px 15px 30px;
}
.title {
  text-align: center;
  font-size: 24px;
}
.wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  background: url(../assets/img/login-background.jpg);
  height: 100vh;
  background-size: cover;
}
.flex {
  display: flex;
  justify-content: space-between;
}
.floor {
  position: fixed;
  bottom: 10px;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
</style>
<style scoped>
</style>